﻿using System;
using System.IO;
using System.Linq;
using System.Web;
using Common;
using Controladores;
using Web.Helpers;
using Web.Pages;
using Entidades;

namespace Web.Handlers
{
    /// <summary>
    /// Summary description for DownloadFileHandler
    /// </summary>
    public class DownloadFileHandler : IGenericHandler
    {
        public enum DownloadTypes
        {
            ScriptDoc = 1,
            ScriptBrk = 2,
            ScriptSrt = 3,
            ScriptBundle = 4
        }

        public void ProcessRequest(HttpContext context)
        {
            // TODO => Lots of duplicated code !! Improve this..
            try
            {
                var idGuion = WellKnownKeys.Entities.DEFAULT_ID;
                var importacion = default(GuionImportacion);

                var downloadType = (DownloadTypes)Convert.ToInt32( context.Request.QueryString["downloadType"] );
                switch (downloadType)
                {
                    case DownloadTypes.ScriptBundle:
                        idGuion = Convert.ToInt32( context.Request.QueryString["idGuion"] );
                        importacion = new ControladorBase<GuionImportacion>().ObtenerEntidad( x => x.Guion.Id == idGuion );
                        if (importacion == null)
                            return;
                        var path = Path.Combine( Helpers.FileHelper.GetServerRoot(), Common.WellKnownKeys.Directories.Files.ScriptsUploaded, idGuion.ToString() );
                        var names = new string[] { importacion.BRK, importacion.STR };
                        var fileNames = names.Select(name => String.Format("{0}/{1}", path, name)).ToList();
                        var zipStream = BasePage.CreateZipFile( fileNames.ToArray(), "" );
                        var zipFileName = String.Format("{0}-Ep.{1}.zip",
                            !String.IsNullOrEmpty(importacion.Proyecto) ? importacion.Proyecto : "sin-proyecto",
                            importacion.Episodio.HasValue ? importacion.Episodio.Value.ToString() : "0");
                        zipFileName = Helpers.FileHelper.RemoveIllegalCharsFromFilename(zipFileName);
                        BasePage.StreamFileToBrowser( zipFileName, zipStream.GetBuffer() );
                        break;

                    case DownloadTypes.ScriptDoc:
                        idGuion = Convert.ToInt32( context.Request.QueryString["idGuion"] );
                        
                        importacion = new ControladorBase<GuionImportacion>().ObtenerEntidad( x => x.Guion.Id == idGuion );
                        if (importacion == null)
                            return;
                        var fileName = importacion.DOC;
                        var filePath = Path.Combine( Helpers.FileHelper.GetServerRoot(), Common.WellKnownKeys.Directories.Files.ScriptsUploaded, idGuion.ToString(), fileName );
                        var stream = FileHelper.ReadFileInfoStream( filePath );
                        var buffer = Common.Formatter.IO_Stream.ConvertirEnArray( stream );
                        BasePage.StreamFileToBrowser( fileName, buffer );
                        break;
                }
            }
            catch (Exception ex)
            {
                BasePage.LogError( ex);
            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}